const baseUrl="/";
function get(url,params,success,error){
	return ajax(url,params,"GET",success);
	$.get(baseUrl+url,params,function(data){
		if(data.code===-1){
			localStorage.clear();
		}
		success(data);
	},function(data){
		if(error!=undefined){
			error(data);
		}
	});
}
function post(url,params,success,error){
	return ajax(url,params,"POST",success,error);
}

function postRequestBody(url,params,success,error){
	$.ajax({
		url:baseUrl+url,
		data:params,
		type:"post",
		contentType:"application/json",
		success:function(data){
			if(data.code===-1){
				localStorage.clear();
			}
			success(data);
		},
		error:function(data){
			if(error!=undefined){
				error(data);
			}
		},
	});
}

function ajax(url,params,type,success,error){
	$.ajax({
		url:baseUrl+url,
		data:params,
		type:type,
		dataType:"json",
		traditional:true,
		headers : { 'Accept' : 'application/json','Content-Type' : 'application/json;charset=utf-8'}, //接口json格式
		success:function(data){
			if(data.code===-1){
				localStorage.clear();
			}
			success(data);
		},
		error:function(data){
			if(error!=undefined){
				error(data);
			}
		},
	});
}

/**
 * [fileLengthFormat 格式化文件大小]
 * @param  {[int]} total [文件大小]
 * @param  {[int]} n     [total参数的原始单位如果为Byte，则n设为1，如果为kb，则n设为2，如果为mb，则n设为3，以此类推]
 * @return {[string]}       [带单位的文件大小的字符串]
 */
function fileLengthFormat(total, n) {
    var format;
    var len = total / (1024.0);
    if (len > 1000) {
        return arguments.callee(len, ++n);
    } else {
        switch (n) {
            case 1:
                format = len.toFixed(2);
                break;
            case 2:
                format = len.toFixed(2);
                break;
            case 3:
                format = len.toFixed(2);
                break;
            case 4:
                format = len.toFixed(2);
                break;
        }
        return format;
    }
}

function formatTime(time) {
	if (typeof time !== 'number' || time < 0) {
		return time
	}

	var hour = parseInt(time / 3600)
	time = time % 3600
	var minute = parseInt(time / 60)
	time = time % 60
	var second = time

	return ([hour, minute, second]).map(function (n) {
		n = n.toString()
		return n[1] ? n : '0' + n
	}).join(':')
}

function dateFormat(fmt, date) {
    let ret;
    let opt = {
        "Y+": date.getFullYear().toString(),        // 年
        "m+": (date.getMonth() + 1).toString(),     // 月
        "d+": date.getDate().toString(),            // 日
        "H+": date.getHours().toString(),           // 时
        "M+": date.getMinutes().toString(),         // 分
        "S+": date.getSeconds().toString()          // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp("(" + k + ")").exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
        };
    };
    return fmt;
}

function formatLocation(longitude, latitude) {
	if (typeof longitude === 'string' && typeof latitude === 'string') {
		longitude = parseFloat(longitude)
		latitude = parseFloat(latitude)
	}

	longitude = longitude.toFixed(2)
	latitude = latitude.toFixed(2)

	return {
		longitude: longitude.toString().split('.'),
		latitude: latitude.toString().split('.')
	}
}
var dateUtils = {
	UNITS: {
		'年': 31557600000,
		'月': 2629800000,
		'天': 86400000,
		'小时': 3600000,
		'分钟': 60000,
		'秒': 1000
	},
	humanize: function (milliseconds) {
		var humanize = '';
		for (var key in this.UNITS) {
			if (milliseconds >= this.UNITS[key]) {
				humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
				break;
			}
		}
		return humanize || '刚刚';
	},
	format: function (dateStr) {
		var date = this.parse(dateStr)
		var diff = Date.now() - date.getTime();
		if (diff < this.UNITS['天']) {
			return this.humanize(diff);
		}
		var _format = function (number) {
			return (number < 10 ? ('0' + number) : number);
		};
		return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' +
			_format(date.getHours()) + ':' + _format(date.getMinutes());
	},
	parse: function (str) { //将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
		var a = str.split(/[^0-9]/);
		return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
	}
};

function getCurrentMonthFirst() {
	var date = new Date()
	date.setDate(1)
	return date
}

function getCurrentMonthLast() {
	var date = new Date();
	var currentMonth = date.getMonth();
	var nextMonth = ++currentMonth;
	var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
	var oneDay = 1000 * 60 * 60 * 24;
	return new Date(nextMonthFirstDay - oneDay);
}

function format(fmt, date) {
	var o = {
		"M+": date.getMonth() + 1, //月份
		"d+": date.getDate(), //日
		"h+": date.getHours(), //小时
		"m+": date.getMinutes(), //分
		"s+": date.getSeconds(), //秒
		"q+": Math.floor((date.getMonth() + 3) / 3), //季度
		"S": date.getMilliseconds() //毫秒
	};
	if (/(y+)/.test(fmt))
		fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
	for (var k in o)
		if (new RegExp("(" + k + ")").test(fmt))
			fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
	return fmt;
}

function currentDate() {
	var d = new Date();
	var year = d.getFullYear();
	var month = d.getMonth() + 1;
	var date = d.getDate();
	var day = d.getDay();
	var curDateTime = year;
	if (month > 9)
		curDateTime = curDateTime + "-" + month;
	else
		curDateTime = curDateTime + "-0" + month;
	if (date > 9)
		curDateTime = curDateTime + "-"  + date;
	else
		curDateTime = curDateTime + "-0" + date;
	return curDateTime;
}

function currentYearMonth() {
	let d = new Date();
	let year = d.getFullYear();
	let month = d.getMonth() + 1;
	let currentYearMonth = year;
	if (month > 9)
		currentYearMonth = currentYearMonth +"年"+ month+"月";
	else
		currentYearMonth = currentYearMonth +"年"+ month+"月";
	return currentYearMonth;
}

function afterFiveYearDate() {
	var d = new Date();
	var year = d.getFullYear()+5;
	var month = d.getMonth() + 1;
	var date = d.getDate();
	var day = d.getDay();
	var curDateTime = year;
	if (month > 9)
		curDateTime = curDateTime + "-" + month;
	else
		curDateTime = curDateTime + "-0" + month;
	if (date > 9)
		curDateTime = curDateTime + "-"  + date;
	else
		curDateTime = curDateTime + "-0" + date;
	return curDateTime;
}

function tt() {
	 var d = new Date();
       var year = d.getFullYear();
       var month = d.getMonth() + 1;
       var date = d.getDate();
       var day = d.getDay();
       var curDateTime = year;
       if (month > 9)
          curDateTime = curDateTime + "" + month;
       else
          curDateTime = curDateTime + "0" + month;
       if (date > 9)
          curDateTime = curDateTime + ""  + date;
       else
          curDateTime = curDateTime + "0" + date;
       return curDateTime;
}

function formatYMdHms(d) {
	var year = d.getFullYear();
	var month = d.getMonth() + 1;
	var date = d.getDate();
	var day = d.getDay();
	var curDateTime = year+"-";
	if (month > 9){
		curDateTime = curDateTime + "" + month;
	}else{
		curDateTime = curDateTime + "0" + month;
	}
	curDateTime+="-";
	if (date > 9){
		curDateTime = curDateTime + ""  + date;
	}else{
		curDateTime = curDateTime + "0" + date;
	}
	return curDateTime;
}

function alert(msg)
{
	layer.msg(msg);
};

function consoleLog(msg){
	console.log(msg);
}

//DES加密
function encryptByDES(message, key){
	var keyHex = CryptoJS.enc.Utf8.parse(key);
	var encrypted = CryptoJS.DES.encrypt(message, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	return encrypted.ciphertext.toString();
}
//DES解密
function decryptByDES(ciphertext, key){
	var keyHex = CryptoJS.enc.Utf8.parse(key);
	var decrypted = CryptoJS.DES.decrypt({
		ciphertext: CryptoJS.enc.Hex.parse(ciphertext)
	}, keyHex, {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	var result_value = decrypted.toString(CryptoJS.enc.Utf8);
	return result_value;
}
//加密
function encryptLocalStorage(jsonData,key)
{
	if(key==undefined  || key==null){key='12qwaszx';}
	let data=JSON.stringify(jsonData);
	let wordArray = CryptoJS.enc.Utf8.parse(data);
	let base64 = CryptoJS.enc.Base64.stringify(wordArray);
	let result=encryptByDES(base64,key);
	return result;
}
//解密
function decryptLocalStorage(data,key)
{
	if(key==undefined || key==null){key='12qwaszx';}
	let _data=decryptByDES(data,key);
	let parsedWordArray = CryptoJS.enc.Base64.parse(_data);
	let result= parsedWordArray.toString(CryptoJS.enc.Utf8);
	return JSON.parse(result);
}

function checkLogin(layer)
{
	let u=localStorage.getItem("ADMIN_LOGIN");
	let loginU={};
	if(u==undefined){
		layer.msg('请登录', {icon: 1, time: 500},function () {window.location = 'logout';});
		return;
	}else{
		loginU=decryptLocalStorage(u);
	}
	request.token({token:loginU.token},function(data) {
		if(data.data==0){
			layer.msg('请登录', {icon: 1, time: 500},function () {window.location = 'logout';});
			return;
		}else{
			localStorage.setItem("ADMIN_LOGIN", encryptLocalStorage(loginU));
		}
	});
}

function getNowFormatDate() {
	let date = new Date();
	let sep= "-";
	let month = date.getMonth() + 1;
	let strDate = date.getDate();
	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	let currentDate = date.getFullYear() + sep + month + sep + strDate;
	return currentDate;
}

function setTableHeight()
{
	setTimeout(function(){
		let windowHeight=$(window).height();
		let tableFieldset=$(".table-search-fieldset").height();
		if(tableFieldset=='' || tableFieldset==undefined)
		{
			tableFieldset=0;
		}
		$(".layui-table-body").height(windowHeight-tableFieldset-190);

		$(window).resize(function() {
			let windowHeight=$(window).height();
			let tableFieldset=$(".table-search-fieldset").height();
			if(tableFieldset=='' || tableFieldset==undefined)
			{
				tableFieldset=0;
			}
			$(".layui-table-body").height(windowHeight-tableFieldset-190);
		});
	},300);
}

function setWorkPlanTrColor(completeDate,startDate,deadlineDate,i)
{
	//提前完成的浅绿；正常完成绿色；超期完成的黄色
	if(completeDate!=null && completeDate!='' && completeDate!=undefined)
	{
		//完成日期
		completeDate=completeDate.replaceAll("-", "")
		let _completeDate=parseInt(completeDate);
		//开始日期
		startDate=startDate.replaceAll("-", "")
		let _startDate=parseInt(startDate);
		//最后期限
		deadlineDate=deadlineDate.replaceAll("-", "")
		let _deadlineDate= parseInt(deadlineDate);
		if(_completeDate<_startDate)
		{
			//提前完成的浅绿
			$("tr[data-index='" + i + "']").attr({"style":"color:#19b955"});
		}
		if(_completeDate>=_startDate && _completeDate<=_deadlineDate)
		{
			//正常完成绿色
			$("tr[data-index='" + i + "']").attr({"style":"color:green"});
		}
		if(_completeDate>_deadlineDate)
		{
			//超期完成的黄色
			$("tr[data-index='" + i + "']").attr({"style":"color:orange"});
		}

	}
}

function searchFieldset()
{
	let show=$('.search-display-btn').attr("show");
	let searchFieldsetStatus=localStorage.getItem("searchFieldsetStatus");
	if(searchFieldsetStatus!=undefined && searchFieldsetStatus!=''){
		show=searchFieldsetStatus;
	}
	if(show=='0')
	{
		localStorage.setItem("searchFieldsetStatus","1");
		$('.search-display-btn').attr("show","1");
		$('.search-display-btn').html('<i class="fa fa-angle-up"></i>折叠');
		$($('.layui-form')[0]).show();
	}else{
		localStorage.setItem("searchFieldsetStatus","0");
		$('.search-display-btn').attr("show","0");
		$('.search-display-btn').html('<i class="fa fa-angle-down"></i>展开');
		$($('.layui-form')[0]).hide();
	}
	setTableHeight();
}

function checkip(ip)
{
	var pcount = 0
	var ip_length = ip.length
	var ip_letters = "1234567890."
	for (p=0; p < ip_length; p++)
	{
		var ip_char = ip.charAt(p)
		if (ip_letters.indexOf(ip_char) == -1)
		{
			return false
		}
	}
	for (var u = 0; u < ip_length; u++) { (ip.substr(u,1) == ".") ? pcount++ : pcount }
	if(pcount != 3) { return false }
	firstp = ip.indexOf(".")
	lastp = ip.lastIndexOf(".")
	str1 = ip.substring(0,firstp)
	ipstr_tmp = ip.substring(0,lastp)
	secondp = ipstr_tmp.lastIndexOf(".")
	str2 = ipstr_tmp.substring(firstp+1,secondp)
	str3 = ipstr_tmp.substring(secondp+1,lastp)
	str4 = ip.substring(lastp+1,ip_length)
	if (str1 == '' || str2 == '' || str3 == '' || str4 == '') { return false }
	if (str1.length > 3 || str2.length > 3 || str3.length > 3 || str4.length > 3) { return false }
	if (str1 <= 0 || str1 > 255) { return false }
	else if (str2 < 0 || str2 > 255) { return false }
	else if (str3 < 0 || str3 > 255) { return false }
	else if (str4 < 0 || str4 > 255) { return false }
	return true
}


//度转度°分′秒″
function ToDegrees(val) {
	if (typeof (val) == "undefined" || val == "") {
		return "";
	}
	var i = val.indexOf('.');
	var strDu = i < 0 ? val : val.substring(0, i);//获取度
	var strFen = 0;
	var strMiao = 0;
	if (i > 0) {
		var strFen = "0" + val.substring(i);
		strFen = strFen * 60 + "";
		i = strFen.indexOf('.');
		if (i > 0) {
			strMiao = "0" + strFen.substring(i);
			strFen = strFen.substring(0, i);//获取分
			strMiao = strMiao * 60 + "";
			i = strMiao.indexOf('.');
			strMiao = strMiao.substring(0, i + 4);//取到小数点后面三位
			strMiao = parseFloat(strMiao).toFixed(2);//精确小数点后面两位
		}
	}
	return strDu + "," + strFen + "," + strMiao;    // 这里可以修改成你想要的格式例如你可以
	//    改成这样的：return strDu + "°" + strFen + "'" + strMiao + "\"N";

}

//度°分′秒″转度
function ToDigital(strDu, strFen, strMiao, len) {
	len = (len > 6 || typeof (len) == "undefined") ? 6 : len;//精确到小数点后最多六位
	strDu = (typeof (strDu) == "undefined" || strDu == "") ? 0 : parseFloat(strDu);
	strFen = (typeof (strFen) == "undefined" || strFen == "") ? 0 : parseFloat(strFen) / 60;
	strMiao = (typeof (strMiao) == "undefined" || strMiao == "") ? 0 : parseFloat(strMiao) / 3600;
	var digital = strDu + strFen + strMiao;
	if (digital == 0) {
		return "";
	} else {
		return digital.toFixed(len);
	}
}


function getGreatCircleDistance(lat1, lng1, lat2, lng2) {
	var EARTH_RADIUS = 6378137.0;
	var PI = Math.PI;

	function getRad(d) {
		return d * PI / 180.0;
	}
	var radLat1 = getRad(lat1);
	var radLat2 = getRad(lat2);

	var a = radLat1 - radLat2;
	var b = getRad(lng1) - getRad(lng2);

	var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
	s = s * EARTH_RADIUS;
	s = Math.round(s * 10000) / 10000.0;

	return s;    // 公里数
}

/**
 * 预处理判断 某个点是否在某个区域
 * @param {*} lng
 * @param {*} lat
 * @param {*} points such as '120.133446,30.271645||120.133153,30.271669||120.133138,30.271595||'
 */
function preceedPointInArea(lng, lat, points) {
	var parking_gps = points
	var gpsStringArray = parking_gps.split('||')
	var polygon = []
	for (var index in gpsStringArray) {
		var item = gpsStringArray[index]
		var point = item.split(',')
		if (point.length == 2) {
			point['lng'] = parseFloat(point[0])
			point['lat'] = parseFloat(point[1])
			polygon.push(point)
		}
	}
	var flag = isPointInPolygon(polygon, lng, lat)

	return flag;
}



/**
 * 某个点是否在某个区域
 */
function isPointInPolygon(polygon, lng, lat) {
	var numberOfPoints = polygon.length;
	var polygonLats = [];
	var polygonLngs = [];
	for (var i = 0; i < numberOfPoints; i++) {
		polygonLats.push(polygon[i]['lat']);
		polygonLngs.push(polygon[i]['lng']);
	}
	var polygonContainsPoint = false;
	for (var node = 0, altNode = (numberOfPoints - 1); node < numberOfPoints; altNode = node++) {
		if ((polygonLngs[node] > lng != (polygonLngs[altNode] > lng))
			&& (lat < (polygonLats[altNode] - polygonLats[node])
				* (lng - polygonLngs[node])
				/ (polygonLngs[altNode] - polygonLngs[node])
				+ polygonLats[node]
			)
		) {
			polygonContainsPoint = !polygonContainsPoint;
		}
	}

	return polygonContainsPoint;
}

function getUrlParams(url) {
	let urlStr = url.split('?')[1]
	let result = Qs.parse(urlStr)
	return result;
}


